<template>
  <div class="enterprise-info">
    <div class="box">
      <el-form
        ref="baseFormName"
        inline
        :rules="companyRules"
        label-width="120px"
        :disabled="isInfoEdit"
        class="base-form"
        :model="formData"
      >
        <el-row v-for="(item, index) in companyBaseInfo" :key="index">
          <el-col :span="it.span" v-for="(it, idx) in item" :key="idx">
            <el-form-item
              :class="{'line-height': it.lineHeight}"
              :style="{'margin-left': it.left}"
              :label="it.label"
              v-if="
                it.prop != 'invoiceLimit' ||
                  (it.prop == 'invoiceLimit' &&
                    formData['hasDistributionService'] == 1)
              "
              :prop="it.prop"
            >
              <el-input
                v-if="it.type === 'autocomplete'"
                v-model="formData[it.prop]"
                :placeholder="it.placeholder"
                :disabled="isEditItem(it)"
              />
              <!-- autocomplete输入框 -->
              <!-- input输入框 -->
              <el-input
                v-else-if="it.type === 'input'"
                v-model="formData[it.prop]"
                :maxlength="it.maxlength ? it.maxlength : null"
                :placeholder="it.placeholder"
                :disabled="isEditItem(it)"
              />
              <!-- 单选 -->
              <el-radio-group
                v-else-if="it.type === 'radio'"
                v-model="formData[it.prop]"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
              <!-- 复选 -->
              <el-checkbox-group
                v-else-if="it.type === 'checkbox'"
                v-model="formData[it.prop]"
              >
                <el-checkbox
                  v-for="(itm, idx) in checkboxList"
                  :key="idx"
                  :label="itm.val"
                  >{{ itm.lab }}</el-checkbox
                >
              </el-checkbox-group>
              <!-- textarea -->
              <el-input
                v-else-if="it.type === 'textarea'"
                type="textarea"
                maxlength="1000"
                show-word-limit
                rows="4"
                v-model="formData[it.prop]"
                :placeholder="it.placeholder"
              />
              <!-- 时间 -->
              <el-date-picker
                v-else-if="it.type === 'date'"
                v-model="formData[it.prop]"
                type="date"
                value-format="yyyy-MM-dd"
                :placeholder="it.placeholder"
              />
              <!-- 下拉选择 -->
              <el-select
                v-else-if="it.type === 'select' && it.otherProp === 'PCA'"
                v-model="formData[it.prop]"
                disabled
                :placeholder="it.placeholder"
              >
                <el-option
                  v-for="itm in defaultcountry"
                  :key="itm.value"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
              <el-select
                v-else-if="it.type === 'select' && it.otherProp === 'PCAA'"
                v-model="formData[it.prop]"
                @change="initCity"
                :placeholder="it.placeholder"
              >
                <el-option
                  v-for="itm in areaObj.provinceCode"
                  :key="itm.value"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
              <el-select
                v-else-if="it.type === 'select' && it.otherProp === 'PCAAA'"
                v-model="formData[it.prop]"
                @change="initCountry"
                :placeholder="it.placeholder"
              >
                <el-option
                  v-for="itm in areaObj.cityCode"
                  :key="itm.value"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
              <el-select
                v-else-if="it.type === 'select' && it.otherProp === 'PCAAAA'"
                v-model="formData[it.prop]"
                :placeholder="it.placeholder"
              >
                <el-option
                  v-for="itm in areaObj.countyCode"
                  :key="itm.value"
                  :label="itm.label"
                  :value="itm.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import {codeAreaList} from '@const/aggregationCenterApi'
import {getAcCompanyBaseNew, updateAcCompanyBaseNew} from '@const/api_auth.js'
export default {
  name: 'EnterPriseInfo',
  data() {
    return {
      companyRules: {
        fullName: [
          {required: true, message: '请输入公司名称', trigger: 'blur'}
        ],
        unifiedSocialCreditCode: [
          {required: true, message: '请输入统一社会信用代码', trigger: 'blur'}
        ],
        linkMan: [{required: true, message: '请输入联系人', trigger: 'change'}],
        linkPhone: [
          {required: true, message: '请正确填写联系电话', trigger: 'blur'}
        ],
        // countryCode: [
        //   {required: true, message: '请选择所在国家', trigger: 'change'}
        // ],
        // provinceCode: [
        //   {required: true, message: '请选择所在省份', trigger: 'change'}
        // ],
        // cityCode: [
        //   {required: true, message: '请选择所在城市', trigger: 'change'}
        // ],
        // countyCode: [
        //   {required: true, message: '请选择所在县区', trigger: 'change'}
        // ],
        // businessScope: [
        //   {required: true, message: '请选择经营业务范围', trigger: 'change'}
        // ],
        receiveAddress: [
          {required: true, message: '请输入收发件地址', trigger: 'blur'}
        ],
        warehouseAddress: [
          {required: true, message: '请输入库房地址', trigger: 'blur'}
        ],
        // invoiceLimit: [
        //   {pattern: /\d/, message: '请输入数字的发票限额', trigger: 'blur'}
        // ],
        address: [{required: true, message: '请输入公司地址', trigger: 'blur'}],
        // businessScopeDes: [
        //   {required: true, message: '请输入经营范围', trigger: 'blur'}
        // ],
        president: [
          {required: true, message: '请输入法定代表人', trigger: 'blur'}
        ],
        presidentPhone: [
          {required: true, message: '请输入正确的电话', trigger: 'blur'}
        ],
        presidentEmail: [
          {required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        linkManEmail: [
          {required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        // postCode: [
        //   {pattern: /^[0-9]{6}$/, message: '请输入正确的邮编', trigger: 'blur'}
        // ],
        email: [
          {required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
        ]
      },
      isInfoEdit: false,
      defaultcountry: [{label: '中国', value: '86'}],
      areaObj: {
        provinceCode: [],
        cityCode: [],
        countyCode: []
      },
      checkboxList: [
        {lab: '一类医疗器械', val: '1'},
        {lab: '二类医疗器械', val: '2'},
        {lab: '三类医疗器械', val: '3'}
      ], // 企业信息复选框的内容
      formData: {
        fullName: '', // 公司全名
        unifiedSocialCreditCode: '', // 统一社会信用代码
        shortName: '', // 公司简称
        linkMan: '', // 联系人
        linkPhone: '', // 联系人电话
        countryCode: '86', // 国家
        provinceCode: '', // 省份
        cityCode: '', // 城市
        countyCode: '', // 县区
        address: '', // 注册地址
        introduce: '', // 公司简介
        createDate: '', // 成立时间
        companyPhone: '', // 公司电话
        email: '', // 邮箱
        postCode: '', // 公司邮编
        job: '', // 职务
        president: '', // 总经理
        presidentPhone: '', // 总经理手机
        presidentEmail: '', // 总经理邮箱
        linkManEmail: '', // 联系人邮箱
        receiveAddress: '', // 收发件地址
        invoiceLimit: '', // 发票限额，只能输入数字
        organization: '', // 组织架构
        businessScope: [], // 经营范围
        businessScopeDes: '',
        hasDistributionService: 1 // 是否有配送业务
      }, // 基础信息表单
      companyBaseInfo: [
        [
          {
            prop: 'fullName',
            span: 16,
            placeholder: '请输入',
            label: '公司名称',
            type: 'autocomplete'
          },
          {
            prop: 'createDate',
            span: 8,
            placeholder: '请输入',
            label: '成立日期',
            type: 'date'
          }
        ],
        [
          {
            prop: 'shortName',
            span: 16,
            placeholder: '请输入',
            label: '公司简称',
            type: 'input'
          },
          {
            prop: 'unifiedSocialCreditCode',
            span: 8,
            lineHeight: true,
            placeholder: '请输入',
            label: '统一社会信用代码',
            type: 'input'
          }
        ],
        [
          {
            prop: 'companyPhone',
            span: 8,
            placeholder: '请输入',
            label: '公司电话',
            type: 'input'
          },
          {
            prop: 'postCode',
            span: 8,
            placeholder: '请输入',
            label: '公司邮编',
            type: 'input'
          },
          {
            prop: 'email',
            span: 8,
            placeholder: '请输入',
            label: '公司邮箱',
            type: 'input'
          }
        ],
        [
          {
            prop: 'president',
            span: 8,
            placeholder: '请输入',
            label: '法定代表人',
            type: 'input'
          },
          {
            prop: 'presidentPhone',
            span: 8,
            placeholder: '请输入',
            label: '法定代表人电话',
            type: 'input'
          },
          {
            prop: 'presidentEmail',
            span: 8,
            placeholder: '请输入',
            label: '法定代表人邮箱',
            type: 'input'
          }
        ],
        [
          {
            prop: 'linkMan',
            span: 8,
            placeholder: '请输入',
            label: '联系人',
            type: 'input'
          },
          {
            prop: 'linkPhone',
            span: 8,
            placeholder: '请输入',
            label: '联系人电话',
            type: 'input'
          },
          {
            prop: 'linkManEmail',
            span: 8,
            placeholder: '请输入',
            label: '联系人邮箱',
            type: 'input'
          }
        ],
        [
          {
            prop: 'countryCode',
            span: 6,
            placeholder: '请输入',
            label: '国家',
            type: 'select',
            otherProp: 'PCA'
          },
          {
            prop: 'provinceCode',
            span: 6,
            placeholder: '请输入',
            label: '所在省份',
            type: 'select',
            otherProp: 'PCAA'
          },
          {
            prop: 'cityCode',
            span: 6,
            placeholder: '请输入',
            label: '所在城市',
            type: 'select',
            otherProp: 'PCAAA'
          },
          {
            prop: 'countyCode',
            span: 6,
            placeholder: '请输入',
            label: '所在县区',
            type: 'select',
            otherProp: 'PCAAAA'
          }
        ],
        [
          {
            prop: 'businessScope',
            span: 16,
            placeholder: '请输入',
            label: '经营业务范围',
            type: 'checkbox'
          },
          {
            prop: 'hasDistributionService',
            lineHeight: true,
            span: 8,
            placeholder: '请输入',
            label: '是否为医院直接配送商',
            type: 'radio'
          }
        ],
        [
          {
            prop: 'receiveAddress',
            span: 16,
            placeholder: '请输入',
            label: '收发件地址',
            type: 'input'
          },
          {
            prop: 'invoiceLimit',
            span: 8,
            placeholder: '请输入',
            label: '发票限额(元)',
            type: 'input'
          }
        ],
        [
          {
            prop: 'warehouseAddress',
            span: 16,
            placeholder: '请输入',
            maxlength: '100',
            label: '库房地址',
            type: 'input'
          },
          {
            prop: 'ouCode',
            span: 8,
            placeholder: '请输入',
            maxlength: '20',
            label: 'OU实体代码',
            type: 'input'
          }
        ],
        [
          {
            prop: 'address',
            lineHeight: true,
            span: 16,
            placeholder: '请输入',
            label: '公司地址（与营业执照一致）',
            type: 'input'
          },
        ],
        [
          {
            prop: 'businessScopeDes',
            lineHeight: true,
            span: 16,
            placeholder: '请输入',
            label: '经营范围',
            type: 'textarea'
          }
        ],
        [
          {
            prop: 'introduce',
            span: 16,
            placeholder: '请输入',
            label: '公司简介',
            type: 'textarea'
          }
        ]
      ]
    }
  },
  created() {
    this._initGlobalBtn()
    this.getCompanyBaseInfo()
  },
  methods: {
    _initGlobalBtn() {
      let obj = {}
      obj = {
        type: 'btn',
        arr: [{type: 'primary', val: '保存', handle: this.globalSubmitSave}]
      }
      this.$store.commit('changeLayoutHandle', obj)
    },
    globalSubmitSave() {
      this.$refs['baseFormName'].validate(valid => {
        if (valid) {
          this.$axios({
            method: 'post',
            url: updateAcCompanyBaseNew,
            data: {
              ...this.formData,
              businessScope: this.formData.businessScope.join(','),
              // 下面这种写法，纯属偷懒，正常开发绝对不允许这么写
              province: this.areaObj['provinceCode'].filter(item => {
                if (item.value === this.formData.provinceCode) {
                  return item
                }
              })[0] ? this.areaObj['provinceCode'].filter(item => {
                if (item.value === this.formData.provinceCode) {
                  return item
                }
              })[0].label : '',
              city: this.areaObj['cityCode'].filter(item => {
                if (item.value === this.formData.cityCode) {
                  return item
                }
              })[0] ? this.areaObj['cityCode'].filter(item => {
                if (item.value === this.formData.cityCode) {
                  return item
                }
              })[0].label : '',
              county: this.areaObj['countyCode'].filter(item => {
                if (item.value === this.formData.countyCode) {
                  return item
                }
              })[0] ? this.areaObj['countyCode'].filter(item => {
                if (item.value === this.formData.countyCode) {
                  return item
                }
              })[0].label : ''
            }
          }).then(res => {
            if (res.data.payload && res.data.code === '0') {
              this.$message({type: 'success', message: '保存成功！'})
              this.getCompanyBaseInfo()
            }
          })
        }
      })
    },
    // 某个字段是否允许编辑
    isEditItem(it) {
      return ['fullName', 'companyName', 'unifiedSocialCreditCode'].includes(
        it.prop
      )
    },
    // 通过企业code获取企业信息
    getCompanyBaseInfo() {
      let companyId = this.$store.state.companyId
      this.$axios({
        methods: 'get',
        url: getAcCompanyBaseNew,
        params: {
          id: companyId
        }
      }).then(res => {
        let result = res.data.payload
        if (result) {
          this.formData = result
          this.formData.businessScope = result.businessScope
            ? result.businessScope.split(',')
            : []
          this.formData.countryCode = '86';
          // this.formData.hasDistributionService = this.formData.hasDistributionService ? this.formData.hasDistributionService : 1
          // 通过接口获取省市级联动数据
          this.initProvince()
          this.initCity(false)
          this.initCountry(false)
        }
      })
    },
    initProvince() {
      //  默认确定国家是中国,获取省
      this.$axios({
        method: 'get',
        url: codeAreaList,
        params: {
          countryCode: 86
        }
      }).then(res => {
        let objEntriesArr = Object.entries(
          res.data.payload ? res.data.payload : {}
        )
        if (objEntriesArr.length) {
          this.areaObj.provinceCode = objEntriesArr.map(item => {
            return {
              value: item[0],
              label: item[1]
            }
          })
        }
      })
    },
    // 省变动，获取市
    initCity(flag) {
      this.$axios({
        method: 'get',
        url: codeAreaList,
        params: {
          provinceCode: this.formData.provinceCode
        }
      }).then(res => {
        if (flag) {
          this.areaObj.cityCode = []
          this.areaObj.countyCode = []
          this.formData.cityCode = ''
          this.formData.countyCode = ''
        }
        let objEntriesArr = Object.entries(
          res.data.payload ? res.data.payload : {}
        )
        if (objEntriesArr.length) {
          this.areaObj.cityCode = objEntriesArr.map(item => {
            return {
              value: item[0],
              label: item[1]
            }
          })
        }
      })
    },
    // 市变动，获取区
    initCountry(flag) {
      this.$axios({
        method: 'get',
        url: codeAreaList,
        params: {
          cityCode: this.formData.cityCode
        }
      }).then(res => {
        if (flag) {
          this.areaObj.countyCode = []
          this.formData.countyCode = ''
        }
        let objEntriesArr = Object.entries(
          res.data.payload ? res.data.payload : {}
        )
        if (objEntriesArr.length) {
          this.areaObj.countyCode = objEntriesArr.map(item => {
            return {
              value: item[0],
              label: item[1]
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less">
.enterprise-info {
  .box {
    background: #fff !important;
    // 企业基本信息
    margin-bottom: 20px;
    .el-form-item {
      display: flex;
      .el-form-item__content {
        flex: 1;
        .el-date-editor {
          width: 100%;
        }
        .el-select {
          width: 100%;
        }
        .el-autocomplete {
          width: 100%;
        }
      }
    }
    // 其他特殊属性
    .line-height {
      .el-form-item__label {
        line-height: 16px;
      }
    }
  }
}
</style>
